package com.mbigger.sigar.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mbigger.sigar.bean.CpuUsage;
import com.mbigger.sigar.bean.DiskUsage;
import com.mbigger.sigar.bean.MemUsage;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SigarService implements SystemInformationService {

    @Autowired
    private Sigar sigar;

    @Override
    public CpuUsage getCpuInfo() {
        return getGeneralCpuUsage();
    }

    private CpuUsage getGeneralCpuUsage() {
        CpuUsage cpuUsage = new CpuUsage();
        cpuUsage.setName("General");
        cpuUsage.setTime(new Date());
        try {
            CpuPerc cpu = sigar.getCpuPerc();
            int value = (int) (cpu.getCombined()*100);
            cpuUsage.setUsedPercent(value);
        } catch (SigarException e) {
            log.warn("{}", e.getMessage());
            cpuUsage.setUsedPercent(0);
        }
        return cpuUsage;
    }

    @Override
    public List<DiskUsage> getDiskUsage() {
        List<DiskUsage> list = new ArrayList<>();
        try {
            FileSystem fslist[] = sigar.getFileSystemList();
            for (FileSystem fs : fslist) {
                // 只处理本地文件系统，否则中止，下一个
                if (fs.getType() != FileSystem.TYPE_LOCAL_DISK)
                    break;
                FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
                DiskUsage du = new DiskUsage();
                du.setName(fs.getDevName());
                du.setUsedPercent(usage.getUsePercent());
                du.setTime(new Date());
                list.add(du);
            }
        } catch (SigarException e) {
            log.warn("{}", e.getMessage());
        }
        return list;
    }

    @Override
    public MemUsage getMemInfo() {
        MemUsage memUsage = new MemUsage();
        memUsage.setName("mem");
        memUsage.setTime(new Date());
        try {
            Mem mem = sigar.getMem();
            memUsage.setUsedPercent(mem.getUsedPercent());
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return memUsage;
    }

}
